import { App, getCurrentInstance, Plugin } from "vue";
import { _RouteLocationBase, Router } from "vue-router";
import PageTabUtil from "@/utils/PageTabUtil";

export function useTabUtil() {
  return getCurrentInstance().appContext.config.globalProperties.$tabUtil;
}

/** 页面缓存插件 */
export default <Plugin<any[]>>{
  install: function (app: App) {
    const $bus = app.config.globalProperties.$bus;
    const $router: Router = app.config.globalProperties.$router;

    const tabUtil = new PageTabUtil();
    app.config.globalProperties.$tabUtil = tabUtil;

    const fixedTabs = $router
      .getRoutes()
      .filter(item => item.meta.tabFixed)
      .map(config => $router.resolve(config));
    tabUtil.addFixedTabs(fixedTabs);

    // TODO: 调试固定标签页
    tabUtil.addFixedTabs([
      $router.resolve("/setting/field?typeId=1"),
      $router.resolve("/list/Project"),
      $router.resolve("/view/1")
    ]);

    $router.beforeEach(route => {
      tabUtil.onRouterChange(route);
      $bus.emit('tabsChange', tabUtil.tabs);
    });
  }
}

declare module "vue-router" {
  interface RouteMeta {
    tabName?: MetaFuncValue;
    tabFixed?: boolean;
  }
}

declare module "@vue/runtime-core" {
  interface ComponentCustomProperties {
    $tabUtil: PageTabUtil;
  }
}
